package com.acme.bankapp.service.bank;

import java.util.ArrayList;

import com.acme.bankapp.domain.bank.Client;
import com.acme.bankapp.domain.bank.ClientRegistrationListener;

public class EmailNotificationListenerClass implements ClientRegistrationListener {
	
	private static final String TEST_DOMAIN = "@test.test";
	private static final long serialVersionUID = 1L;
	private MyQueue<Email> emailQueue;
	private ArrayList<EmailSendRunner> emailSendRunners;
	
	public EmailNotificationListenerClass() {
		super();
		this.emailQueue = new MyQueue<Email>();
		this.emailSendRunners = new ArrayList<EmailSendRunner>();
		for (int i=0; i<10; i++) {
			EmailSendRunner curRunner = new EmailSendRunner();
			this.emailSendRunners.add(curRunner);
			curRunner.start();
		}
		
	}

	@Override
	public void onClientAdded(Client client) {
		sendNotificationEmailForClient(client);
	}
	
	public void sendNotificationEmailForClient(Client client) {
		Email email = new Email(client, client.getClientSalutation() + TEST_DOMAIN);
		emailQueue.add(email);
	}
	
	public class EmailSendRunner extends Thread {
		@Override
		public void run() {
			if (!emailQueue.isEmpty()) {
				emailQueue.enque();
				try {
					sleep(10000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
}